package com.fate.framework.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
public class TreeNode {
  /** {name:"编号", isForm:0} */
  @Schema(description = "编号")
  private Object id;

  /** {name:"父部门ID，一级部门为0"} */
  @Schema(description = "父节点id，最顶级节点pid为0")
  private Object pid;

  /** {name:"排序"} */
  @Schema(description = "序号，children里的排序，从小到大排序")
  private Integer orderNumber;

  /**
   * 根据目标节点id递归获取所有直接和间接子节点
   *
   * @param allNodeList 存储所有节点信息的列表
   * @param id 目标节点id
   * @param targetNodeList 存储所有直接和间接子节点的列表
   * @param <T> TreeNode类的子类
   */
  public static <T extends TreeNode> void listAllSubNodesById(
      List<T> allNodeList, Object id, List<T> targetNodeList) {
    List<T> childList = allNodeList.stream().filter(node -> id.equals(node.getPid())).toList();
    childList.forEach(
        node -> {
          targetNodeList.add(node);
          listAllSubNodesById(allNodeList, node.getId(), targetNodeList);
        });
  }

  public static <T extends TreeNode> List<T> listAllSubNodesById(List<T> allNodeList, Object id) {
    List<T> targetList = new ArrayList<>();
    listAllSubNodesById(allNodeList, id, targetList);
    return targetList;
  }

  public static <T extends TreeNode> List<T> listAllSubNodesAndSelf(
      List<T> allNodeList, Object id) {
    List<T> targetList = listAllSubNodesById(allNodeList, id);
    List<T> self = allNodeList.stream().filter(node -> id.equals(node.getId())).toList();
    targetList.addAll(self);

    return targetList;
  }
}
